package com.lcredu.spring.ioc;

import com.lcredu.spring.annotation.Autowired;
import com.lcredu.spring.annotation.Component;
import com.lcredu.spring.annotation.ComponentScan;
import com.lcredu.spring.annotation.Scope;
import com.lcredu.spring.processe.BeanPostProcessor;
import com.lcredu.spring.processe.InitializingBean;
import org.apache.commons.lang.StringUtils;


import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 黎长容
 * @date 2025-07-14 15:04
 * 作用 : 充当容器
 */
public class LcrSpringApplicationContext {
    private Class configClass;
    //创建存放Bean信息的集合
    private ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();
    //创建存放单例的集合(singletonObjects)
    private ConcurrentHashMap<String, Object> singletonObjects = new ConcurrentHashMap<>();
    //创建储存后置处理器的arrayList;   一般情况下还是存放在Map中
    private List<BeanPostProcessor> beanPostProcessors = new ArrayList<>();

    //构造器
    public LcrSpringApplicationContext(Class configClass) {
        //完成扫描
        beansDefinitionByScan(configClass);

        //通过beanDefinitionMap,初始化单例池
        Enumeration<String> keys = beanDefinitionMap.keys();
        while (keys.hasMoreElements()) {
            //获取到beanName
            String beanName = keys.nextElement();
            //获取到beanDefinition,进行scope判断
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            String scope = beanDefinition.getScope();
            if ("singleton".equals(scope)) {
                //创建对象放入单例池
                Object object = createBean(beanDefinition, beanName);
                singletonObjects.put(beanName, object);
            }
        }
//        System.out.println("beanDefinitionMap=" + beanDefinitionMap);
//        System.out.println("singletonObjects=" + singletonObjects);


    }


    private Object createBean(BeanDefinition beanDefinition, String beanName) {
        Class clazz = beanDefinition.getClazz();

        try {
            Object instance = clazz.getDeclaredConstructor().newInstance();

            //依赖注入
            //1.扫描所有的字段
            for (Field declaredField : clazz.getDeclaredFields()) {
                //2.判断字段上面有没有Autowired注解
                if (declaredField.isAnnotationPresent(Autowired.class)) {
                    //3.得到这个属性名
                    String name = declaredField.getName();
                    //4.通过getBean方法来获取要组装的对象
                    Object object = getBean(name);
                    //5.进行组装
                    //6.例如给service组装一个dao
                    //7.爆破
                    declaredField.setAccessible(true);
                    declaredField.set(instance, object);

                }
            }

            //在初始化之前调用后置处理器的before方法
            for (BeanPostProcessor beanPostProcessor : beanPostProcessors) {
                //在控制处理器的before方法可以对bean进行处理
                Object current = beanPostProcessor.postProcessBeforeInitialization(instance, beanName);
                if (current != null) {
                    instance = current;
                }
            }


            //这里可以对进行初始化方法的操作--刚好创建好这个bean的时候
            //这里调用初始化,如果 bean 实现了 InitializingBean
            System.out.println("======创建好了====" + instance);
            if (instance instanceof InitializingBean) {
                try {
                    ((InitializingBean) instance).afterPropertiesSet();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

            //在初始化之后调用后置处理器的after方法
            for (BeanPostProcessor beanPostProcessor : beanPostProcessors) {
                //在控制处理器的before方法可以对bean进行处理
                Object current = beanPostProcessor.postProcessAfterInitialization(instance, beanName);
                if (current != null) {
                    instance = current;
                }
            }


            System.out.println("-----------------------------------");

            if (instance != null) {
                return instance;
            } else {
                return null;
            }
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }


    }


    public void beansDefinitionByScan(Class configClass) {

        this.configClass = configClass;
//        System.out.println("configClass = " + this.configClass);

        //获取要扫描的包
        //1.获取扫描包注解的配置
        ComponentScan componentScan = (ComponentScan) this.configClass.getDeclaredAnnotation(ComponentScan.class);
        //2.获取要扫描的包
        String path = componentScan.value();
        System.out.println("要扫描的包=" + path);


        //获取扫描包下所有的class文件
        //1. 得到一个类的加载器:app类加载器
        ClassLoader classLoader = LcrSpringApplicationContext.class.getClassLoader();

        //2. 通过类的加载器获取到要扫描包的URL
        path = path.replace(".", "/");
        URL url = classLoader.getResource(path);

        //3.将要加载的资源(.class)进行遍历=>io
        File file = new File(url.getFile());
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                System.out.println("===================================");
//                System.out.println(f.getAbsolutePath());
                String filePath = f.getAbsolutePath();
                //只处理class文件
                if (filePath.endsWith(".class")) {
                    //为了进行反射,需要获取到com.lcredu.component
                    //D:\Code\JavaCode\Spring\spring_quick_start\target\classes\com\lcredu\component\UserService.class
                    String className = filePath.substring(filePath.lastIndexOf("\\") + 1, filePath.lastIndexOf("."));
                    //获取类的全路径
                    path = path.replace("/", ".");
                    String classFullName = path + "." + className;
                    //进行反射?
                    //进行过滤,判断该类是不是需要注入到容器中
                    try {
                        Class<?> clazz = classLoader.loadClass(classFullName);
                        //如果这个类使用Component注解就是bean
                        if (clazz.isAnnotationPresent(Component.class)) {

                            //如果扫描到了就放入
                            //这里不能用instanceof 因为他不是一个实例化对象
                            //判断当前的clazz有没有实现BeanPostProcessor接口
                            if (BeanPostProcessor.class.isAssignableFrom(clazz)) {
                                BeanPostProcessor beanPostProcessor = (BeanPostProcessor) clazz.newInstance();
                                beanPostProcessors.add(beanPostProcessor);
                                continue;
                            }

                            System.out.println("这是一个spring bean=" + clazz + "   类名:   " + className);
                            //1.获取到他的id
                            Component componentAnnotation = clazz.getDeclaredAnnotation(Component.class);
                            String componentValue = componentAnnotation.value();
                            //如果我的value值为空就不好了
                            //这里可以做一个默认值
                            if ("".equals(componentValue)) {
                                componentValue = StringUtils.uncapitalize(className);
                            }

                            //2.放入BeanDefinition
                            BeanDefinition beanDefinition = new BeanDefinition();
                            beanDefinition.setClazz(clazz);

                            //3.获取到scope
                            if (clazz.isAnnotationPresent(Scope.class)) {
                                //如果我有这个范围注解
                                Scope scopeAnnotation = clazz.getDeclaredAnnotation(Scope.class);
                                beanDefinition.setScope(scopeAnnotation.value());
                            } else {
                                //如果没有,默认为单例
                                beanDefinition.setScope("singleton");
                            }

                            //4.放入beanDefinitionMap
                            beanDefinitionMap.put(componentValue, beanDefinition);
                        } else {
                            System.out.println("这不是一个spring bean=" + clazz + "   类名:   " + className);
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }

            }
        }


    }

    //返回容器对象
    public Object getBean(String name) {
        //如果有这个键
        if (beanDefinitionMap.containsKey(name)) {
            BeanDefinition beanDefinition = beanDefinitionMap.get(name);
            //获取范围
            if ("singleton".equals(beanDefinition.getScope())) {
                //如果是单例,则直接在map集合中取
                return singletonObjects.get(name);
            } else {
                //如果是多例
                return createBean(beanDefinition, name);
            }
        } else {
            throw new NullPointerException(name + "找不到");
        }
    }
}
